<template>
  <div class="user-avatar" :class="[sizeClass, { circle }]">
    <el-avatar 
      v-if="user && (user.name || user.username)" 
      :src="avatarUrl" 
      :size="avatarSize"
      :class="circle ? 'circle-avatar' : ''"
    >
      {{ getInitials }}
    </el-avatar>
    <el-avatar v-else :size="avatarSize" :class="circle ? 'circle-avatar' : ''">
      <el-icon><User /></el-icon>
    </el-avatar>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { User } from '@element-plus/icons-vue'
import type { User as UserType } from '@/types/user'
import { getAvatarUrl } from '@/utils/avatar'

interface Props {
  user?: UserType | null
  size?: 'small' | 'medium' | 'large'
  circle?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  user: null,
  size: 'medium',
  circle: false
})

const sizeClass = computed(() => `user-avatar--${props.size}`)

const avatarSize = computed(() => {
  switch (props.size) {
    case 'small': return 24
    case 'large': return 48
    default: return 32
  }
})

const getInitials = computed(() => {
  if (!props.user) return ''
  
  const name = props.user.name || props.user.username || ''
  if (!name) return ''
  
  // 获取姓名或用户名的首字母，支持中英文
  const firstChar = name.charAt(0)
  return firstChar.toUpperCase()
})

// 获取处理后的头像URL
const avatarUrl = computed(() => {
  if (!props.user?.avatar) {
    // 如果没有头像，返回undefined，让el-avatar显示首字母
    return undefined
  }
  const url = getAvatarUrl(props.user.avatar)
  // 如果URL为空字符串，返回undefined，让el-avatar显示首字母
  return url || undefined
})
</script>

<style scoped>
.user-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.user-avatar--small {
  font-size: 12px;
}

.user-avatar--medium {
  font-size: 14px;
}

.user-avatar--large {
  font-size: 16px;
}

.circle-avatar {
  border-radius: 50%;
}
</style>